<template>
  <div class="container dark-theme" @click="closeMenuOnClickOutside">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="logo">“沈誉通”信用生活综合系统</div>
      <div class="nav">
        <router-link to="/credit-life">信用生活</router-link>
        <router-link to="/credit-business">信用商业</router-link>
        <router-link to="/behavior">亲社会行为</router-link>
        <router-link to="/news">新闻资讯</router-link>
        <router-link to="/credit-management">信用管理</router-link>
      </div>
      <div class="user-menu" ref="userMenu">
        <div class="avatar-box">
          <img :src="user.icon || require('@/imgs/icons/default-icon.png')" class="avatar" alt="用户头像"
            @click.stop="toggleMenu" />
        </div>
        <div v-if="isMenuOpen" class="dropdown-menu">
          <div class="menu-item" @click="goToProfile">个人信息</div>
          <div class="menu-item" @click="logout">退出登录</div>
        </div>
      </div>
    </div>


    <!-- 用户信息卡片视图 -->
    <el-card class="box-card">
      <el-form :model="user" :rules="rules" label-width="150px" ref="userForm">

        <el-form-item label="用户昵称: " prop="nickName">
          <el-input class="sci-fi-input" v-model="user.nickName"></el-input>
        </el-form-item>

        <el-form-item label="电话: " prop="phone">
          <el-input class="sci-fi-input" v-model="user.phone" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱: " prop="email">
          <el-input class="sci-fi-input" v-model="user.email"></el-input>
        </el-form-item>

        <el-form-item label="性别: " prop="gender">
          <el-select v-model="user.gender" placeholder="请选择">
            <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="年龄: " prop="age">
          <el-input-number class="sci-fi-input" v-model="user.age"></el-input-number>
        </el-form-item>

        <el-form-item label="职业: " prop="job">
          <el-select v-model="user.job" placeholder="请选择">
            <el-option v-for="item in jobOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="收入: " prop="income">
          <el-input-number class="sci-fi-input" v-model="user.income"></el-input-number>
        </el-form-item>

        <el-form-item label="地址: " prop="address">
          <el-select v-model="user.address" placeholder="请选择">
            <el-option v-for="item in addressOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="用户头像: ">
          <el-upload class="avatar-uploader" action="http://localhost:8089/res/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="user.icon" :src="user.icon" class="avatar">
            <img v-else src="@/imgs/icons/default-icon.png" class="avatar">
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="sci-fi-button" @click="submitForm">提交修改</el-button>
          <el-button type="primary" class="sci-fi-button" @click="verifyIdentity">实名认证</el-button>
        </el-form-item>

      </el-form>
    </el-card>

  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';

export default {
  name: 'UserInformation',
  data() {
    const validateIdNumber = (rule, value, callback) => {
      const reg = /(^\d{17}(\d|X|x)$)/;
      if (!value) {
        callback(new Error('请输入身份证号'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入有效的18位身份证号'));
      } else {
        callback();
      }
    };

    return {
      verifyRules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '姓名长度在2到10个字符',
            trigger: 'blur',
          },
        ],
        idNumber: [
          { required: true, validator: validateIdNumber, trigger: 'blur' },
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' },
        ],
      },

      verifyForm: {
        realName: '',
        idNumber: '',
        createTime: '',
      },

      rules: {
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, type: 'number', min: 1, max: 120, message: '请输入年龄', trigger: 'blur' }
        ],
        income: [
          { required: true, type: 'number', min: 0, message: '请输入收入', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        job: [
          { required: true, message: '请选择职业', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请选择地址', trigger: 'change' }
        ]
      },

      genderOptions: [{
        value: 1,
        label: '男'
      }, {
        value: 2,
        label: '女'
      }, {
        value: 3,
        label: '保密'
      }],

      jobOptions: [{
        value: '学生',
        label: '学生'
      }, {
        value: '公务员',
        label: '公务员'
      }, {
        value: '私营个体',
        label: '私营个体'
      }, {
        value: '企业职员',
        label: '企业职员'
      }, {
        value: '退休人员',
        label: '退休人员'
      }, {
        value: '军人',
        label: '军人'
      }, {
        value: '其他',
        label: '其他'
      }],

      addressOptions: [{
        value: '和平区',
        label: '和平区'
      }, {
        value: '沈河区',
        label: '沈河区'
      }, {
        value: '大东区',
        label: '大东区'
      }, {
        value: '皇姑区',
        label: '皇姑区'
      }, {
        value: '铁西区',
        label: '铁西区'
      }, {
        value: '苏家屯区',
        label: '苏家屯区'
      }, {
        value: '浑南区',
        label: '浑南区'
      }, {
        value: '沈北新区',
        label: '沈北新区'
      }, {
        value: '于洪区',
        label: '于洪区'
      }, {
        value: '辽中区',
        label: '辽中区'
      }, {
        value: '康平区',
        label: '康平区'
      }, {
        value: '法库区',
        label: '法库区'
      }, {
        value: '新民区',
        label: '新民区'
      }],

      user: {
        id: '',
        nickName: '',
        gender: null,
        age: null,
        job: null,
        income: null,
        address: null,
        icon: ''
      },

      isMenuOpen: false,  // 控制点击头像后的下拉菜单是否显示
      isVerified: false,
    };
  },
  created() {
    this.getUserBasicInfo();
    this.getVerificationStatus();
  },
  methods: {
    verifyIdentity() {
      this.$router.push('/verification');
    },

    async getVerificationStatus() {
      try {
        const { data } = await axios.get('/users/user-info/status', {
          headers: { Authorization: `${localStorage.getItem('token')}` },
        });
        if (data.success && data.data) {
          this.isVerified = true;
          this.verifyForm = {
            realName: data.data.realName,
            idNumber: data.data.idNumber,
            createTime: data.data.createTime,
          };
        } else {
          this.isVerified = false;
        }
      } catch (err) {
        this.$message.error('获取认证状态失败：' + err.message);
      }
    },

    submitVerification() {
      this.$refs.verifyFormRef.validate(async (valid) => {
        if (!valid) return;
        try {
          const { data } = await axios.post('/users/user-info', this.verifyForm, {
            headers: { Authorization: `${localStorage.getItem('token')}` },
          });
          if (data.success) {
            this.$message.success('实名认证成功！');
            await this.getVerificationStatus();
          } else {
            this.$message.error('实名认证失败：' + data.errorMsg);
          }
        } catch (err) {
          this.$message.error('实名认证失败：' + err.message);
        }
      });
    },

    submitForm() {
      console.log('submit')

      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // 验证通过，调用接口提交数据
          this.updateUserInfo();
        } else {
          this.$message.error('请完善表单信息');
          return false;
        }
      });
    },
    async updateUserInfo() {
      try {
        const res = await axios.post('/users/user/update', this.user, {
          headers: { Authorization: localStorage.getItem('token') }
        });
        if (res.data.success) {
          this.$message.success('修改成功');
        }
      } catch (err) {
        this.$message.error('修改失败：' + err.message);
      }
    },


    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.user.icon = res.data.url
        console.log(this.user.icon)
        Message("头像上传成功")
      } else {
        this.user.icon = null
        Message("头像上传失败")
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },


    formatGender(gender) {
      return gender === 1 ? '男' : gender === 2 ? '女' : '未知';
    },
    toggleMenu() {
      this.isMenuOpen = !this.isMenuOpen;
    },
    closeMenuOnClickOutside(event) {
      const menu = this.$refs.userMenu;
      if (menu && !menu.contains(event.target)) {
        this.isMenuOpen = false;
      }
    },
    goToProfile() {
      this.$router.push('/user-information');
      this.isMenuOpen = false;
    },
    logout() {
      axios.post('/users/user/logout')
        .then(() => {
          sessionStorage.removeItem('token');
          this.$router.push('/login-code');
        })
        .catch(err => this.$message.error('退出登录失败：' + err.message));
    },

    async getUserBasicInfo() {
      await axios.get('/users/user/basic', {
        headers: { Authorization: `${localStorage.getItem('token')}` }
      }).then((res) => {
        console.log(res.data)
        if (res.data.success) {
          this.user = res.data.data
        }
      }).catch((err) => {
        this.$message.error('获取用户信息失败：' + err.message);
      })
    },
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  color: #fff;
  font-family: "Microsoft YaHei", sans-serif;
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  padding: 10px 30px;
  background: #002d52;
  align-items: center;
}

.logo {
  font-size: 20px;
  color: #4fc3f7;
}

.nav a {
  margin: 0 10px;
  color: #fff;
  text-decoration: none;
}

.nav a:hover {
  color: #4fc3f7;
}

.user-menu {
  position: relative;
}

.avatar-box img.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #4fc3f7;
}

.dropdown-menu {
  position: absolute;
  top: 50px;
  right: 0;
  width: 120px;
  background: #002d52;
  border: 1px solid #4fc3f7;
  border-radius: 4px;
  z-index: 10;
}

.menu-item {
  padding: 10px;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}

.menu-item:hover {
  background: #014b75;
}

.box-card {
  margin: 20px;
  background: #13263a;
  border-radius: 10px;
}

.sci-fi-input .el-input__inner {
  background: #001e3c;
  border: 1px solid #4fc3f7;
  color: #fff;
}

.sci-fi-button {
  background: #00ccff;
  border: none;
  color: #001c3e;
}

.sci-fi-button:hover {
  background: #014b75;
}


/* 上传按钮样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>